package io.gitee.thant.utils;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

public class ArrayBuilder<T> {
	private List<T[]> _lst = new ArrayList<T[]>();
	private int _sz = 0;
	private Class<T> _cls;
	
	public ArrayBuilder(Class<T> ts) {
		_cls = ts;
	}
	
	public ArrayBuilder<T> append(T[] data) {
		if (null != data && data.length>0) {
			_lst.add(data);
			_sz += data.length;
		}
		return this;
	}

	@SuppressWarnings("unchecked")
	public ArrayBuilder<T> append(T b) {
		T[] t = (T[])Array.newInstance(b.getClass(), 1);
		t[0] = b;
		return append(t);
	}
	
	public T[] toArrayRef() {
		setLength(_sz);
		return (T[])_lst.get(0);
	}
	
	@SuppressWarnings("unchecked")
	public ArrayBuilder<T> setLength(int len) {
		if (len>=0) {
			T[] target = (T[])Array.newInstance(_cls, len);
			
			for(int i=0, p=0; p<len && i<_lst.size(); ++i) {
				T[] ba = _lst.get(i);
				if (p+ba.length<len) {
					System.arraycopy(ba, 0, target, p, ba.length);
					p += ba.length;
				} else {
					System.arraycopy(ba, 0, target, p, len-p);
					p += len-p;
				}
			}
			
			_lst.clear();
			_lst.add(target);
			_sz = len;
		}
		return this;
	}
	
	public int size() {
		return _sz;
	}
}
